package com.hengxinguotong.zhihuichengjian.ui.security;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AccidentAddPersonAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Company;
import com.hengxinguotong.zhihuichengjian.bean.OneCompanyRes;
import com.hengxinguotong.zhihuichengjian.bean.SecurityAccident;
import com.hengxinguotong.zhihuichengjian.bean.Structure;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.AddPersonnelActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonnelActivity;
import com.hengxinguotong.zhihuichengjian.ui.SearchPersonActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.StructureActivity;
import com.hengxinguotong.zhihuichengjian.ui.quality.QualityTestActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.SelectListPop;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;


/**
 * 质量事故报告  安全事故报告
 * Created by liux on 2017/3/7.
 */

public class SecurityAccidentActivity extends BaseActivity implements AualityTestAddPicAdapter.OnRecyclerViewClickListener,
        RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.tv_title_name)
    HXTextView tvTitleName;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.save_test)
    HXTextView saveTest;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.date_tv)
    HXTextView dateTv;
    @BindView(R.id.check_date_rl)
    RelativeLayout checkDateRl;
    @BindView(R.id.structure_tv)
    HXTextView structureTv;
    @BindView(R.id.company_rl)
    RelativeLayout companyRl;
    @BindView(R.id.company_tv)
    HXTextView companyTv;
    @BindView(R.id.team_tv)
    HXTextView teamTv;
    @BindView(R.id.team_rl)
    RelativeLayout teamRl;
    @BindView(R.id.contacts_tv)
    HXTextView contactsTv;
    @BindView(R.id.tel_rl)
    RelativeLayout telRl;
    @BindView(R.id.contacts_moblie_tv)
    HXTextView contactsMoblieTv;
    @BindView(R.id.test_project_etv)
    HXEditTextView testProjectEtv;
    @BindView(R.id.test_result_etv)
    HXEditTextView testResultEtv;
    @BindView(R.id.injured_title)
    HXTextView injuredTitle;
    @BindView(R.id.no_injured_tv)
    HXTextView noInjuredTv;
    @BindView(R.id.injured_person_rv)
    RecyclerView injuredPersonRv;
    @BindView(R.id.death_title)
    HXTextView deathTitle;
    @BindView(R.id.no_death_tv)
    HXTextView noDeathTv;
    @BindView(R.id.death_personnel_rv)
    RecyclerView deathPersonnelRv;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.commonly)
    RadioButton commonly;
    @BindView(R.id.serious)
    RadioButton serious;
    @BindView(R.id.major)
    RadioButton major;
    @BindView(R.id.bigness)
    RadioButton bigness;
    @BindView(R.id.accident_result_rg)
    RadioGroup accidentResultRg;
    @BindView(R.id.result_tv)
    HXTextView resultTv;
    @BindView(R.id.accident_ll)
    LinearLayout accidentLl;
    @BindView(R.id.main_sv)
    ScrollView mainSv;
    private AualityTestAddPicAdapter aualityTestAddPicAdapter;
    private AccidentAddPersonAdapter injuredAdapter;
    private AccidentAddPersonAdapter deathAdapter;
    private Structure structure;
    private List<String> paths;
    private List<String> minPaths;
    private List<User> injuredUsers;
    private List<User> deathUsers;
    private AlertDialog dialog;
    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    private int type = 1;//1 质量检查  2安全检查
    private int checked = -1;
    private String interfaceString;
    private SecurityAccident securityAccident;
    private Company company;
    private Company.DataBean group;
    private SelectListPop mSelectListPop;
    private int selectTeamPosition = -1;
    private User selectUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_security_accident);
        type = getIntent().getIntExtra("type", Constants.QUALITY);
        securityAccident = (SecurityAccident) getIntent().getSerializableExtra("securityaccident");
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        if (securityAccident != null) {
            saveTest.setVisibility(View.GONE);
            checkDateRl.setEnabled(false);
//            dateTv.setText(securityAccident.getCreateTime());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            testProjectEtv.setLayoutParams(params);
            testResultEtv.setLayoutParams(params);
            dateTv.setText(securityAccident.getBusinessDate());
            Utils.setEditTextViewUnable(securityAccident.getItems(), testProjectEtv);
            Utils.setEditTextViewUnable(securityAccident.getResults(), testResultEtv);
            Utils.setEditTextViewUnable(securityAccident.getProjectStructureName(), structureTv);
            if(null != securityAccident.getProjectCompanyName()){
                companyRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(securityAccident.getProjectCompanyName(), companyTv);
            }
            if(null != securityAccident.getTeamName()){
                teamRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(securityAccident.getTeamName(), teamTv);
            }
            Utils.setEditTextViewUnable(securityAccident.getContactName(), contactsTv);
            if(null != securityAccident.getContactMobile()){
                telRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(securityAccident.getContactMobile(), contactsMoblieTv);
            }
            Utils.disableRadioGroup(accidentResultRg);
            accidentResultRg.check(getAccidentResById(securityAccident.getStatus()));
            switch (securityAccident.getStatus()){
                case 1:
                    resultTv.setText("一般");
                    resultTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                    break;
                case 2:
                    resultTv.setText("较大");
                    resultTv.setTextColor(getResources().getColor(R.color.color_ffc065));
                    break;
                case 3:
                    resultTv.setText("重大");
                    resultTv.setTextColor(getResources().getColor(R.color.color_f1636a));
                    break;
                case 4:
                    resultTv.setText("特别重大");
                    resultTv.setTextColor(getResources().getColor(R.color.color_c9222a));
                    break;
            }
            switch (type) {
                case Constants.QUALITY:
//                    tvTitleName.setText("质量事故报告");
                    injuredTitle.setVisibility(View.GONE);
                    injuredPersonRv.setVisibility(View.GONE);
                    deathTitle.setVisibility(View.GONE);
                    deathPersonnelRv.setVisibility(View.GONE);
                    if (securityAccident.getPicList().size() == 0) {
                        noPicTv.setVisibility(View.VISIBLE);
                    } else {
                        paths = securityAccident.getPicList();
                        aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
                        addPicRv.setLayoutManager(getLinearLayoutManager());
                        addPicRv.setAdapter(aualityTestAddPicAdapter);
                    }
                    break;
                case Constants.SECURITY:
//                    tvTitleName.setText("安全事故报告");
                    if (securityAccident.getPicList().size() == 0) {
                        noPicTv.setVisibility(View.VISIBLE);
                    } else {
                        paths = securityAccident.getPicList();
                        aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, false);
                        addPicRv.setLayoutManager(getLinearLayoutManager());
                        addPicRv.setAdapter(aualityTestAddPicAdapter);
                    }

                    if (securityAccident.getDeathPersons().size() == 0) {
                        noDeathTv.setVisibility(View.VISIBLE);
                    } else {
                        deathAdapter = new AccidentAddPersonAdapter(this, securityAccident.getDeathPersons(), new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                            @Override
                            public void onItemClick(View v, int position) {
//                                Intent intent = new Intent(SecurityAccidentActivity.this, PersonnelActivity.class);
                                Intent intent = new Intent(SecurityAccidentActivity.this, AddPersonnelActivity.class);
                                intent.putExtra("type", AddPersonnelActivity.MODTYPE);
                                intent.putExtra("personId", securityAccident.getDeathPersons().get(position).getPersonId());
                                startActivity(intent);
                            }

                            @Override
                            public void onClick(View v) {

                            }
                        }, false);
                        deathPersonnelRv.setLayoutManager(getLinearLayoutManager());
                        deathPersonnelRv.setAdapter(deathAdapter);
                    }


                    if (securityAccident.getInjuredPersons().size() == 0) {
                        noInjuredTv.setVisibility(View.VISIBLE);
                    } else {
                        injuredAdapter = new AccidentAddPersonAdapter(this, securityAccident.getInjuredPersons(), new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                            @Override
                            public void onItemClick(View v, int position) {
//                                Intent intent = new Intent(SecurityAccidentActivity.this, PersonnelActivity.class);
                                Intent intent = new Intent(SecurityAccidentActivity.this, AddPersonnelActivity.class);
                                intent.putExtra("type", AddPersonnelActivity.MODTYPE);
                                intent.putExtra("personId", securityAccident.getInjuredPersons().get(position).getPersonId());
                                startActivity(intent);
                            }

                            @Override
                            public void onClick(View v) {

                            }
                        }, false);
                        injuredPersonRv.setLayoutManager(getLinearLayoutManager());
                        injuredPersonRv.setAdapter(injuredAdapter);
                    }
            }
        } else {
            Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            monthOfYear = c.get(Calendar.MONTH);
            dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
            dateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);

            accidentResultRg.setOnCheckedChangeListener(this);
            paths = new ArrayList<String>();
            paths.add(Utils.ADDPIC);
            aualityTestAddPicAdapter = new AualityTestAddPicAdapter(this, paths, this, true);
            addPicRv.setLayoutManager(getLinearLayoutManager());
            addPicRv.setAdapter(aualityTestAddPicAdapter);
            switch (type) {
                case Constants.QUALITY:
//                    tvTitleName.setText("质量事故报告");
                    injuredTitle.setVisibility(View.GONE);
                    injuredPersonRv.setVisibility(View.GONE);
                    deathTitle.setVisibility(View.GONE);
                    deathPersonnelRv.setVisibility(View.GONE);
                    break;
                case Constants.SECURITY:
//                    tvTitleName.setText("安全事故报告");
                    injuredPersonRv.setLayoutManager(getLinearLayoutManager());
                    injuredUsers = new ArrayList<User>();
                    injuredUsers.add(getAddUser());
                    injuredAdapter = new AccidentAddPersonAdapter(this, injuredUsers, new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                        @Override
                        public void onItemClick(View v, int position) {
                            if (injuredUsers.get(position).getHeadPortrait() != null && Utils.ADDPIC.equals(injuredUsers.get(position).getHeadPortrait())) {
                                Intent intent = new Intent(SecurityAccidentActivity.this, SearchPersonActivity.class);
                                intent.putExtra("selectUsers", (Serializable) injuredUsers);
                                intent.putExtra("deathUsers", (Serializable) deathUsers);
                                startActivityForResult(intent, 2);
                            } else {
                                injuredUsers.remove(position);
                                injuredAdapter.notifyDataSetChanged();
                            }

                        }

                        @Override
                        public void onClick(View v) {

                        }
                    }, true);
                    injuredPersonRv.setAdapter(injuredAdapter);

                    deathUsers = new ArrayList<User>();
                    deathUsers.add(getAddUser());
                    deathAdapter = new AccidentAddPersonAdapter(this, deathUsers, new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                        @Override
                        public void onItemClick(View v, int position) {
                            if (Utils.ADDPIC.equals(deathUsers.get(position).getHeadPortrait())) {
                                Intent intent = new Intent(SecurityAccidentActivity.this, SearchPersonActivity.class);
                                intent.putExtra("selectUsers", (Serializable) deathUsers);
                                intent.putExtra("injuredUsers", (Serializable) injuredUsers);
                                startActivityForResult(intent, 3);
                            } else {
                                deathUsers.remove(position);
                                deathAdapter.notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onClick(View v) {

                        }
                    }, true);
                    deathPersonnelRv.setLayoutManager(getLinearLayoutManager());
                    deathPersonnelRv.setAdapter(deathAdapter);
                    break;
            }

        }

    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        structure = (Structure) intent.getSerializableExtra("struct");
//        if (structure != null) {
//            structureTv.setText(structure.getName());
//            clearCompany();
//            getCompany(structure.getId());
//        }

        if (intent.getSerializableExtra("struct") != null) {
            structure = (Structure) intent.getSerializableExtra("struct");
            structureTv.setText(structure.getName());
//            clearCompany();
//            getCompany(structure.getId());
        }

        if(intent.getSerializableExtra("company") != null){
            clearCompany();
            company = (Company) intent.getSerializableExtra("company");
            processCompany(company);
        }

        if(intent.getSerializableExtra("group") != null){
            Company temp = (Company) intent.getSerializableExtra("group");
            processGroup(temp);
        }
    }


    @OnClick({R.id.iv_back, R.id.save_test, R.id.check_date_rl, R.id.structure_tv, R.id.contacts_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.save_test:
                getMinImage();
                break;
            case R.id.check_date_rl:
                showWheelViewDialog();
                break;
            case R.id.structure_tv:
                intent = new Intent(SecurityAccidentActivity.this, StructureActivity.class);
                StructureActivity.FROM = 4;
                startActivity(intent);
                break;
            case R.id.company_tv:
                intent = new Intent(SecurityAccidentActivity.this, CompanyListActivity.class);
                CompanyListActivity.FROM = 2;//1 质量报告、安全报告
                CompanyListActivity.TYPE = 1;//获取公司列表
                startActivity(intent);
                break;
            case R.id.team_tv:
//                intent = new Intent(SecurityAccidentActivity.this, CompanyListActivity.class);
//                CompanyListActivity.FROM = 2;//1 质量报告、安全报告
//                CompanyListActivity.TYPE = 2;//获取班组列表
//                intent.putExtra("projectCompanyId", company.getId());
//                startActivity(intent);
                if (company == null) {
                    return;
                }

                if (company.getData() == null) {
                    return;
                }

                if (company.getData().size() == 0) {
                    return;
                }

                String[] teams = new String[company.getData().size()];
                for (int i = 0; i < company.getData().size(); i++) {
                    teams[i] = company.getData().get(i).getName();
                }
                showSelectPop(teams);
                break;
            case R.id.contacts_tv:
                intent = new Intent(SecurityAccidentActivity.this, PersonLiableListActivity.class);
                String unableUserId = SPUtil.getString(this, "userId");
                intent.putExtra("unableUserId", unableUserId);
                startActivityForResult(intent, 4);
                break;
        }
    }


    private void getMinImage() {
        if (!checkContent()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), this);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    addTest();
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            addTest();
        }
    }

    private void showWheelViewDialog() {
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        SecurityAccidentActivity.this.year = year;
                        SecurityAccidentActivity.this.monthOfYear = monthOfYear;
                        SecurityAccidentActivity.this.dayOfMonth = dayOfMonth;
                        dateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                year, monthOfYear, dayOfMonth).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            switch (requestCode){
                case 1:
                    paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    paths.add(Utils.ADDPIC);
                    if (aualityTestAddPicAdapter != null) {
                        aualityTestAddPicAdapter.setPaths(paths);
                    }
                    break;
                case 2:
                    List<User> temp1 = (List<User>) data.getSerializableExtra("selectUsers");
                    for (int i = 0; i < temp1.size(); i++) {
                        User user = temp1.get(i);
                        if (!user.isInUsers(injuredUsers)) {
                            injuredUsers.add(0, user);
                        }
                    }
                    injuredAdapter.notifyDataSetChanged();
                    break;
                case 3:
                    List<User> temp2 = (List<User>) data.getSerializableExtra("selectUsers");
                    for (int i = 0; i < temp2.size(); i++) {
                        User user = temp2.get(i);
                        if (!user.isInUsers(deathUsers)) {
                            deathUsers.add(0, user);
                        }
                    }
                    deathAdapter.notifyDataSetChanged();
                    break;
                case 4:
                    selectUser = new User();
                    selectUser = (User) data.getSerializableExtra("selectUser");
                    processUser(selectUser);
                    break;
            }
        }
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (securityAccident != null) {
                TaskBigImgActivity.startActivity(SecurityAccidentActivity.this, (ArrayList<String>) paths, position);
            } else {
                paths.remove(position);
                aualityTestAddPicAdapter.notifyDataSetChanged();
            }
        }
    }


    private void addTest() {
        if (!checkContent()) {
            return;
        }
        RequestParams params = new RequestParams();
        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        params.addBodyParameter("type", type + "");
        if(null != structure)
            params.addBodyParameter("projectStructureId", structure.getId());
//        params.addBodyParameter("projectCompanyId", company.getProjectCompanyId());
//        params.addBodyParameter("projectCompanyId", company.getId());
////        params.addBodyParameter("contactId", company.getUserId());
//        params.addBodyParameter("contactId", group.getUserId());
////        params.addBodyParameter("contactMobile", company.getPersonMobile());
//        params.addBodyParameter("contactMobile", group.getMobile());
//        if (company.getProjectCompanyType() == 2) {
////            params.addBodyParameter("teamId", company.getTeamId());
//            params.addBodyParameter("teamId", group.getId());
//        }
        params.addBodyParameter("contactId", selectUser.getUserId());
        if(selectUser.getMobile() != null){
            params.addBodyParameter("contactMobile", selectUser.getMobile());
        }
        if(selectUser.getProjectCompanyId() != null){
            params.addBodyParameter("projectCompanyId", selectUser.getProjectCompanyId());
        }
        if(selectUser.getTeamId() != null){
            params.addBodyParameter("teamId", selectUser.getTeamId());
        }

        params.addBodyParameter("createBy", SPUtil.getString(this, "userId"));

        params.addBodyParameter("accidentDate", year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        params.addBodyParameter("resume", testProjectEtv.getEditableText().toString());
        params.addBodyParameter("firstTreatment", testResultEtv.getEditableText().toString());
        params.addBodyParameter("level", getAccidentIndexById(accidentResultRg.getCheckedRadioButtonId()) + "");


        if (injuredUsers != null && injuredUsers.size() != 0) {
            for (int i = 0; i < injuredUsers.size() - 1; i++) {
                params.addBodyParameter("injuredPersonIds[" + i + "]", injuredUsers.get(i).getPersonId());
            }
        }

        if (deathUsers != null && deathUsers.size() != 0) {
            for (int i = 0; i < deathUsers.size() - 1; i++) {
                params.addBodyParameter("deathPersonIds[" + i + "]", deathUsers.get(i).getPersonId());
            }
        }


        Utils.requestData(getResources().getString(R.string.loading), this, "/accidentReport/save/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                showToast("提交成功");
                setResult(1);
                finish();
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }


    private boolean checkContent() {
//        if (structure == null) {
//            showToast("请选择工程结构");
//            return false;
//        }

//        if(company == null){
//            showToast("请选择分包公司");
//            return false;
//        }

//        if(company != null && company.getType() == 2 && group == null){
//            showToast("班组");
//            return false;
//        }

        if (year == 0) {
            showToast("请选择日期");
            return false;
        }
        if (Utils.isEmpty(testProjectEtv.getEditableText().toString())) {
            showToast("请填写事故详情");
            return false;
        }

        if (Utils.isEmpty(testResultEtv.getEditableText().toString())) {
            showToast("请填写初步处理意见");
            return false;
        }

        if (getAccidentIndexById(accidentResultRg.getCheckedRadioButtonId()) == -1) {
            showToast("请选择事故等级");
            return false;
        }

        if(selectUser == null){
            showToast("请选择责任人");
        }

        return true;

    }


    private int getAccidentIndexById(int res) {
        switch (res) {
            case R.id.commonly:
                return 1;
            case R.id.serious:
                return 2;
            case R.id.major:
                return 3;
            case R.id.bigness:
                return 4;
        }
        return -1;
    }

    private int getAccidentResById(int res) {
        switch (res) {
            case 1:
                return R.id.commonly;
            case 2:
                return R.id.serious;
            case 3:
                return R.id.major;
            case 4:
                return R.id.bigness;
        }
        return -1;
    }


    private User getAddUser() {
        User addUser = new User();
        addUser.setHeadPortrait(Utils.ADDPIC);
        addUser.setPersonId("-1");
        addUser.setName("");
        return addUser;
    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }


    private String[] getPersonIds(List<User> users) {
        String[] persons = new String[users.size()];
        for (int i = 0; i < users.size(); i++) {
            persons[i] = users.get(i).getPersonId();
        }
        return persons;
    }

    private void getCompany(String projectStructureId) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            jsonObject.put("projectStructureId", projectStructureId);
            jsonObject.put("status", "5");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        Utils.requestData(null, this, "/projectCompany/queryByProjectStructionId/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
        Utils.requestData(null, this, "/projectCompany/queryDetailByProjectStructionId/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    OneCompanyRes oneCompanyRes = gson.fromJson(json, OneCompanyRes.class);
                    company = oneCompanyRes.getValue();
                    if (company != null) {
//                        companyTv.setText(company.getProjectCompanyName());
//                        teamTv.setText(company.getTeamName());
//                        contactsTv.setText(company.getPersonName());
//                        contactsMoblieTv.setText(company.getPersonMobile());
                        processCompany(company);
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void processUser(User user){
        contactsTv.setText(user.getName());
        if(user.getMobile() != null){
            telRl.setVisibility(View.VISIBLE);
            contactsMoblieTv.setText(user.getMobile());
        }
        if(user.getProjectCompanyId() != null && user.getProjectCompanyName() != null){
            companyRl.setVisibility(View.VISIBLE);
            companyTv.setText(user.getProjectCompanyName());
        }
        if(user.getTeamId() != null && user.getTeamName() != null){
            teamRl.setVisibility(View.VISIBLE);
            teamTv.setText(user.getTeamName());
        }
    }

    private void processCompany(Company company){
        companyTv.setText(company.getName());
        if(null != company.getData() && company.getData().size() > 0){
            group = company.getData().get(0);
            if(company.getType() == 1){
                teamRl.setVisibility(View.GONE);
            }else if(company.getType() == 2){
                teamRl.setVisibility(View.VISIBLE);
//                teamTv.setText(company.getData().get(0).getName());
            }
//            contactsTv.setText(group.getUserName());
//            contactsMoblieTv.setText(group.getMobile());
        }
    }

    private void processGroup(Company company){
        if(null != company){
            group = new Company.DataBean();
            group.setId(company.getId());
            group.setName(company.getName());
            group.setCompanyId(company.getProjectCompanyId());
            group.setMobile(company.getMobile());
            group.setUserId(company.getUserId());
            group.setUserName(company.getUserName());
            teamTv.setText(company.getName());
            contactsTv.setText(company.getUserName());
            contactsMoblieTv.setText(company.getMobile());
        }
    }

    private void clearCompany() {
        company = null;
        companyTv.setText("");
        teamTv.setText("");
        contactsTv.setText("");
        contactsMoblieTv.setText("");
    }

    private void showSelectPop(final String[] strings) {
        mSelectListPop = new SelectListPop(this, R.layout.dialog_select_sex, strings, new SelectListPop.OnDirListPopItemClicked() {
            @Override
            public void onPopItemClick(int position, String name) {
                selectTeamPosition = position;
                group = company.getData().get(position);
                teamTv.setText(group.getName());
                contactsTv.setText(group.getUserName());
                contactsMoblieTv.setText(group.getMobile());

            }
        });
        mSelectListPop.setFocusable(true);
        mSelectListPop.setOutsideTouchable(true);
        mSelectListPop.setBackgroundDrawable(getResources().getDrawable(R.color.color_transparent));
        mSelectListPop.update();
        mSelectListPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        if (mSelectListPop.isShowing()) {
            mSelectListPop.dismiss();
        } else {
            mSelectListPop.showAtLocation(mainSv, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.commonly:
                resultTv.setText("一般");
                resultTv.setTextColor(getResources().getColor(R.color.color_71e5a2));
                break;
            case R.id.serious:
                resultTv.setText("较大");
                resultTv.setTextColor(getResources().getColor(R.color.color_ffc065));
                break;
            case R.id.major:
                resultTv.setText("重大");
                resultTv.setTextColor(getResources().getColor(R.color.color_f1636a));
                break;
            case R.id.bigness:
                resultTv.setText("特别重大");
                resultTv.setTextColor(getResources().getColor(R.color.color_c9222a));
                break;
        }
    }
}
